
import { Vector2 } from '../math/Vector2'
import {  BasicStyleType } from '../style/BasicStyle'
import {  Object2DType } from './Object2D'
import { Shape2D } from './Shape2D'
const container = document.createElement("div");
container.classList.add('baselinemeasure')
container.innerHTML = `<svg width="10" height="10"
viewBox="0 0 10 10" version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">

</svg>
12`;

const textmeasureEl = document.createElement('span');
textmeasureEl.contentEditable = 'true';
textmeasureEl.classList.add('textSizemeasure')
document.body.append(textmeasureEl);

export const  textSize ={ 
	width:0,
	height:0,
	onChange( ){ 

	}
}

const resizeObserver = new ResizeObserver((entries) => {
	const { width, height } = entries[0].contentRect
	textSize.height = height;
	textSize.width = width ;
	textSize.onChange();
})
resizeObserver.observe(textmeasureEl);


type TextAlign='start' | 'left' | 'center' | 'right' |'end';
type TextType = Object2DType & {
	content: string[],
	textContent: string, //原文本
	offset?: Vector2
	size: Vector2
	view?: View
	style?: BasicStyleType
	fontSize:number
	font?: string 
	lineHeight?:number
	baseLine?: number
	textAlign?:string;
	color?:string;
	
	
	// font 加上fontweight似乎就麻烦了 让浏览器帮我算比较准确
}
// 文字的view,用dom计算出来的
type View = {
	x: number
	y: number
	width: number
	height: number
}

export const fontsInfo = {
	'kaiti':{
	  ascent:220,
	  emSize:256,
	  descent:36,
	},
	'fangsong':{
	  ascent:220,
	  emSize:256,
	  descent:36,
	},
	'songti': { 
		emSize: 1000,
		ascend:1050,
		descend:500 
	}
  }
  

const getDefault =()=> (
	{
	content:[''],
	textContent:'',
	fontSize: 14,
	fontFamily:'楷体',
	font:'楷体 14px',
	lineHeight:22,
	textAlign:'left',
	size: new Vector2(),
	offset: new Vector2(),
	color: '#000000'
})


class Text2D extends Shape2D {
	content = ['']
	textContent='';
	_fontSize = 14;
	fontFamily = '' ;
	font = '楷体';
	baseLine = 0;
	horizontalOffset =0
	lineHeight = 22 ;
	color = '#000';
	// canvasTransform :DOMMatrix ;
	// 类型
	readonly isText = true

	constructor(attr: TextType = getDefault()) {
		const opt =  Object.assign(  getDefault(), attr)
		super()
		this.setOption(opt);
		// this.canvasTransform = //绘制前获取上下文的矩阵

	}

	get fontSize( ){ return this._fontSize}
//  这个计算就暂且放在这里了  虽然计算了尺寸，但是可能因为行高没变  因为我确实没修改这个属性，所以没触发
	set fontSize (val){ 
		if(val !== this._fontSize){
			this._fontSize = val ;
			if( this.content.length){ 
				measureTextSize(this.font , this.lineHeight + 'px', this.content.join('\n'));
				requestAnimationFrame(()=> { 
					
					this.size.set(textmeasureEl.clientWidth,textmeasureEl.clientHeight);
					console.log(...this.size);
				})
			} 
		}
	}

	/* 属性设置 */
	setOption(attr: TextType) {
		for (let [key, val] of Object.entries(attr)) {
			switch (key) {
					case 'style':
					this.style.setOption(val as BasicStyleType)
					break
				default:
					this[key] = val
			}
		}
	}

	/* 绘图 */
	drawShape(ctx: CanvasRenderingContext2D) {
		const { content,color,  view, style,size,textAlign, horizontalOffset,offset,baseLine, lineHeight } = this
		//样式
		style.apply(ctx)
		ctx.font = this.font;
		ctx.textAlign = textAlign;
		ctx.fillStyle = color
		let { x,y}= offset, {width,height} =size ;
		// this.canvasTransform = ctx.getTransform()
		if(view){
			x = view.x ;
			y = view.y;
			width = view.width ;
			height = view.height ;
		}
		// 绘制文字
		for (let i = 0; i < content.length; i++) {
			// 文字是从左下角绘制，所以起点要减去行高
			ctx.fillText(content[i], x+horizontalOffset , y + lineHeight * (i+1) - baseLine,width);
		}
		/* ctx.save()
		ctx.fillStyle = '#0f05'
		ctx.fillRect(x,y,width, height);
		ctx.restore(); */
	}


}


function calcBaseLine(lineHeight:number, fontSize:number, emSize:number, ascent:number,descent:number){
	return (lineHeight + (descent - ascent)* fontSize / emSize )/2 ; 
}

//这种算法，算的就是基线在一行行高中的位置， 就是第一行文本的起点， 
export function measureBaseline  (
    font='',
    lineHeight=22,
  ) {
    container.style.font = font;
    container.style.height = lineHeight+"px";
    container.style.lineHeight = lineHeight+"px";
    document.body.appendChild(container);
  //   这一增一删还是很有必要的， 这样才会让浏览器立即更新dom的尺寸。
    const svg = container.getElementsByTagName('svg')[0]
    const {bottom} = svg.getBoundingClientRect();
    container.remove()
    return bottom;
  };
   //  这里也是想着一帧只更新一次 所以用这个东西，我现在想分离这个 就不能这样了   好像分不了 还是即时计算吧
export  function measureTextSize(font:string , lineHeight:string, content: string){ 
	textmeasureEl.style.font = font ;
	textmeasureEl.style.lineHeight = lineHeight ;
	textmeasureEl.textContent = ''
	textmeasureEl.innerText = content;
	if (content.endsWith('\n')) {
		textmeasureEl.innerText += '0';//这里还不能是空格
	}
}




export { Text2D, calcBaseLine }
  